package pers.cz.freemarker;

import com.alibaba.fastjson.JSON;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * @program: PostGirl-panent
 * @description: FreeMarker
 * @author: Cheng Zhi
 * @create: 2022-04-09 15:47
 **/
public class FreeMarkerUtils {

    public static final String OUTPUT_FOLDER = "./api/";
    /***
     * 创建模板对象
     * @param path 模板文件所在的位置
     * @param ftl 生成的文件名
     * @return
     * @throws Exception
     */
    public static Template loadTemplate(String path, String ftl) throws Exception{
        // 第一步：创建一个Configuration对象，直接new一个对象。构造方法的参数就是freemarker对于的版本号。
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 第二步：设置模板文件所在的路径。
        configuration.setDirectoryForTemplateLoading(new File(path));
        // 第三步：设置模板文件使用的字符集。一般就是utf-8.
        configuration.setDefaultEncoding("utf-8");
        // 第四步：加载一个模板，创建一个模板对象。
        Template template = configuration.getTemplate(ftl);
        return template;
    }

    /**
     * 文件生成
     * @param dataModel
     * @param template
     * @param fileName
     * @throws IOException
     * @throws TemplateException
     */
    public static File writeFile(Map dataModel, Template template, String fileName) throws IOException, TemplateException {

        try {
            //文件夹不存在的话进行创建
            File reportDir= new File(OUTPUT_FOLDER );
            if(!reportDir.exists()&& !reportDir .isDirectory()){
                reportDir.mkdir();
            }
            File file = new File(OUTPUT_FOLDER + "/" + fileName);
            Writer out = new FileWriter(file);
            // 调用模板对象的process方法输出文件。
            template.process(dataModel, out);
            // 关闭流。
            out.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 解析json为Map
    * @param json
     * @return
     */
    public static Map analyzeJson(String json) {

        Map<String, Object> map = (Map) JSON.parse(json);

        Map<String, Set<Field>> myMap = new HashMap<>();
        Stack list = new Stack();
        // 里面存放 key-List list<FirstInput>
        iteratorMap(map, myMap, list);
        return myMap;
    }

    /**
     * 迭代解析Map获取类型
     * @param map
     * @param myMap
     * @param list
     */
    private static void iteratorMap(Map<String, Object> map, Map<String, Set<Field>> myMap, Stack<String> list) {

        for (String key : map.keySet()) {
            if (key.equals("success") ) {
                continue;
            }
            if (map.get(key) instanceof Map) {

                if (list.size() > 0) {
                    String s = list.peek();
                    Field field = new Field(key, "Map", key+"描述");
                    myMap.get(s).add(field);
                }
                if (myMap.get(key) == null) {
                    myMap.put(key,new HashSet<>());
                    list.push(key);
                }
                iteratorMap((Map<String, Object>) map.get(key), myMap, list);
                if (list.size() > 0) {
                    list.pop();
                }
            }

            if (map.get(key) instanceof List) {
                if (list.size() > 0) {
                    String s = list.peek();
                    Field field = new Field(key, "List", key+"描述");
                    myMap.get(s).add(field);
                }
                if (myMap.get(key) == null) {
                    myMap.put(key,new HashSet<Field>());
                    list.push(key);
                }

                Set<String> strings = myMap.keySet();
                Iterator iterator = ((List) map.get(key)).iterator();
                while (iterator.hasNext()) {
                    try {
                        iteratorMap((Map<String, Object>) iterator.next(), myMap, list);
                    } catch (Exception e) {

                    }
                }
                if (list.size() > 0) {
                    list.pop();
                }
            }

            if (map.get(key) instanceof String) {
                if (list.size() > 0) {
                    String s = list.peek();
                    Field firstInput = new Field(key, "String", key+"描述");
                    myMap.get(s).add(firstInput);
                }

            }else if (map.get(key) instanceof Long) {
                if (list.size() > 0) {
                    String s = list.peek();
                    Field firstInput = new Field(key, "Long", key+"描述");
                    myMap.get(s).add(firstInput);
                }

            }else if (map.get(key) instanceof Integer) {
                if (list.size() > 0) {
                    String s = list.peek();
                    Field firstInput = new Field(key, "Integer", key+"描述");
                    myMap.get(s).add(firstInput);
                }

            }else if (map.get(key) instanceof Boolean) {
                if (list.size() > 0) {
                    String s = list.peek();
                    Field firstInput = new Field(key, "Boolean", key+"描述");
                    myMap.get(s).add(firstInput);
                }

            } else if (map.get(key) instanceof Double){
                if (list.size() > 0) {
                    String s = list.peek();
                    Field firstInput = new Field(key, "Double", key+"描述");
                    myMap.get(s).add(firstInput);
                }

            }

        }
    }
}
